<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.courseName"
        placeholder="课程名称"
        style="width: 200px;"
        clearable
      />
      <el-select
        v-model="listQuery.orgId"
        placeholder="所属校区"
        clearable
        style="width: 180px"
        class="filter-item1"
        @change="handleOrgIdChange"
      >
        <el-option
          v-for="option in orgList"
          :key="option.key"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-select
        v-model="listQuery.departmentId"
        placeholder="科系"
        clearable
        style="width: 180px"
        class="filter-item1"
        @change="handleDepartmentIdChange"
      >
        <el-option
          v-for="option in departmentIdOptions"
          :key="option.key"
          :label="option.label"
          :value="option.value"
        />
      </el-select>
      <el-button
        v-waves
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
        >{{ $t("table.search") }}</el-button
      >
      <el-button
        class="filter-item"
        style="margin-left: 10px;"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
        >{{ $t("table.add") }}</el-button
      >
    </div>

    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column label="课程名称" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.courseName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属科系" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.departmentName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属校区" width="" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.organizationName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="" align="center">
        <template slot-scope="scope">
          <span>{{
            scope.row.createTime | parseTime("{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="230"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.current"
      :limit.sync="listQuery.size"
      @pagination="getList"
    />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="userForm"
        :model="userForm"
        :rules="rules"
        label-width="140px"
        class="userForm"
        style="width: 420px; margin-left:0px;"
      >
        <el-form-item label="课程名称" prop="courseName">
          <el-input
            v-model="userForm.courseName"
            placeholder="请输入课程名称"
            maxlength="32"
          />
        </el-form-item>
        <el-form-item label="所属校区" prop="organizationId">
          <el-select
            v-model="userForm.organizationId"
            class="filter-item"
            placeholder="请选择所属校区"
            style="width: 100%;"
            @change="handleFormOrgIdChange"
          >
            <el-option
              v-for="item in orgList"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="所属科系" prop="departmentId">
          <el-select
            v-model="userForm.departmentId"

            placeholder="请选择所属科系"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="option in formDepartmentIdOptions"
              :key="option.key"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{
          $t("table.cancel")
        }}</el-button>
        <el-button
          v-if="dialogStatus == 'create'"
          :loading="submitLoading"
          type="primary"
          @click="createData"
          >{{ $t("table.confirm") }}</el-button
        >
        <el-button v-else :loading="submitLoading" type="primary" @click="updateData">{{
          $t("table.confirm")
        }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  fetchCourseList,
  createCourse,
  deleteCourse,
  updateCourse
} from "@/api/business/course";

import { fetchOrg, fetchCourse } from "@/api/clue";

import waves from "@/directive/waves"; // 水波纹指令
import { parseTime } from "@/utils";

import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

export default {
  name: "UserTable",
  components: { Pagination },
  directives: {
    waves
  },
  filters: {},
  data() {
    return {
      tableKey: 0,
      orgList: null,
      departmentIdOptions: [], //科系
      formDepartmentIdOptions: [],

      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        current: 1,
        size: 20,
        courseName: null,
        departmentId: null,
        organizationId: ""
      },
      dialogFormVisible: false,
      dialogStatus: "",
      textMap: {
        update: "编辑",
        create: "添加"
      },
      userForm: {
        courseId: "",
        courseName: "",
        organizationId: '',
        departmentId: ""
      },
      rules: {
        courseName: [
          { required: true, message: "请输入课程名称", trigger: "blur" },
          { max: 16, message: "请不要超过 16 个字符", trigger: "blur" }
        ],
        organizationId: [
          { required: true, message: "请选择所属校区", trigger: "change" }
        ],
        departmentId: [
          { required: true, message: "请选择所属科系", trigger: "change" }
        ]
      },
      submitLoading: false
    };
  },
  created() {
    this.getList();
    this.getOrgList();
  },
  methods: {
    getList() {
      this.listLoading = true;
      fetchCourseList(this.listQuery).then(response => {
        this.list = response.data;
        this.total = response.count;
        this.listLoading = false;
      });
    },
    getOrgList() {
      this.listLoading = true;
      const queryMethod = "queryChannelType"
      const queryKey = '0'
      fetchOrg(queryMethod,queryKey).then(response => {
        this.orgList = response.data;
        this.listLoading = false;
      });
    },
    handleOrgIdChange(orgId) {
      this.listQuery.departmentId = "";
      this.getDepartmentIdOptions(orgId);
    },
    //科系（校区Id）
    getDepartmentIdOptions(queryId, queryKey) {
      fetchCourse(queryId, "2").then(response => {
        this.departmentIdOptions = response.data;
      });
    },
    handleFormOrgIdChange(orgId) {
      this.userForm.departmentId = "";
      this.getFormDepartmentIdOptions(orgId);
    },
    //科系（校区Id）
    getFormDepartmentIdOptions(queryId, queryKey) {
      fetchCourse(queryId, "2").then(response => {
        this.formDepartmentIdOptions = response.data;
      });
    },

    handleFilter() {
      this.listQuery.current = 1;
      this.getList();
    },
    resetUserForm() {
      this.userForm = {
        courseId: "",
        courseName: "",
        organizationId: "",
        departmentId:''
      };
      this.formDepartmentIdOptions = null;
    },
    handleCreate() {
      this.resetUserForm();
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    createData() {
      this.$refs["userForm"].validate(valid => {
        debugger;
        if (valid) {
          this.submitLoading = true
          createCourse(this.userForm).then(() => {
            this.dialogFormVisible = false
            this.submitLoading = false
            this.handleFilter();
            this.$message({
              message: "创建成功",
              type: "success"
            })
            this.getList()
          }).catch(err => {
            this.submitLoading = false
          })
        }
      });
    },
    handleUpdate(row) {
      this.userForm = Object.assign({}, row); // copy obj
      this.userForm.organizationId = row.organizationId
      this.handleFormOrgIdChange(this.userForm.organizationId)
      this.userForm.departmentId = row.departmentId ;
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["userForm"].clearValidate();
      });
    },
    updateData() {
      this.$refs["userForm"].validate(valid => {
        if (valid) {
          this.submitLoading = true
          updateCourse(this.userForm).then(() => {
            this.dialogFormVisible = false
            this.submitLoading = false
            this.$message({
              message: "更新成功",
              type: "success"
            })
            this.getList()
          }).catch(err => {
            this.submitLoading = false
          })
        }
      });
    },
    handleDelete(row) {
      this.$confirm(
        "此操作将永久删除该数据：" + row.courseName + ", 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      )
        .then(() => {
          this.listLoading = true;
          deleteCourse(row.courseId).then(() => {
            this.listLoading = false;
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            const index = this.list.indexOf(row);
            this.list.splice(index, 1);
          }).catch(err => {
            this.listLoading = false
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v =>
        filterVal.map(j => {
          if (j === "createTime") {
            return parseTime(v[j]);
          } else if (j === "userSex") {
            return this.$options.filters["sexNameFilter"](v[j]);
          } else if (j === "userStatus") {
            return this.$options.filters["statusNameFilter"](v[j]);
          } else {
            return v[j];
          }
        })
      );
    }
  }
};
</script>
